package com.icesoft.wechat.applet.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import cn.hutool.core.util.StrUtil;
import com.icesoft.framework.core.util.JSON;
import com.icesoft.wechat.applet.entity.WechatAuthorizationCode;
import com.icesoft.wechat.applet.service.ApiWechatApplet;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class WechatAppletServiceImpl implements ApiWechatApplet {

	@Override
	public WechatAuthorizationCode decode(String encryptedData, String iv, String code, String rawData, String signature, String appid, String secret) throws Exception {

		WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
		config.setAppid(appid);        //小程序appId
		config.setSecret(secret);    //小程序secret
		config.setMsgDataFormat(StrUtil.trim("JSON"));

		WxMaService wxMaService = new WxMaServiceImpl();
		wxMaService.setWxMaConfig(config);

		WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);

		String openid = sessionInfo.getOpenid();
		String sessionKey = sessionInfo.getSessionKey();

		String decrypt = WxMaCryptUtils.decrypt(sessionKey, encryptedData, iv);

		WechatAuthorizationCode authorizationCode = JSON.parseObject(decrypt, WechatAuthorizationCode.class);
		authorizationCode.setOpenid(openid);
		authorizationCode.setSessionKey(sessionKey);
		return authorizationCode;
	}


}
